﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading.Tasks;

namespace OTDR_OPT
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            InitProductNameBox();
            InitTestStepBox();
            SnBox.Focus();
            ProductManagement.GetInstance().ProductNameListChanged += new EventHandler<ProductListChangedArgs>(ProductListChanged);
        }


        //机型清单发生变化时,刷新可选机型列表
        private void ProductListChanged(object sender,ProductListChangedArgs args) {
            string productname = args.Productname;
            string changeType = args.ChangeType;
            List<string> productnameList = new List<string>();
            App.Current.Dispatcher.Invoke(new Action(() => {
                ItemCollection productNameCollion = ProductNameBox.Items;
                int count = productNameCollion.Count;
                string[] productArr = new string[count];
                productNameCollion.CopyTo(productArr,0);
                productnameList = productArr.ToList();
                if (changeType.Equals("Add"))
                {
                    productnameList.Add(productname);
                }
                else
                {
                    productnameList.Remove(productname);
                }
                ProductNameBox.ItemsSource = null;
                ProductNameBox.ItemsSource = productnameList;
                string selectName = CurrentConfigManagement.GetIntance().GetSelectProductName();
                if (selectName == "")
                {
                    ProductNameBox.SelectedIndex = 0;
                }
                else
                {
                    ProductNameBox.SelectedValue = selectName;
                }
            }));
        }


        //标准光功设置按钮点击时，弹出标准光功窗口
        private void SetSampleMeterMenu_Click(object sender, RoutedEventArgs e)
        {
            SampleMeterEdit sampleMeterEdit = new SampleMeterEdit();
            sampleMeterEdit.Owner = this;
            sampleMeterEdit.ShowDialog();
        }


        //光纤修正按钮点击时，弹出光纤修正界面
        private void FiberCorrectionMenu_Click(object sender,RoutedEventArgs e) {
            FiberCorrectionEdit fiberCorrectionEdit = new FiberCorrectionEdit();
            fiberCorrectionEdit.Owner = this;
            fiberCorrectionEdit.ShowDialog();
        }


        //设置线性点按钮点击时，弹出线性点设置框
        private void SetCheckPointMenu_Click(object sender, RoutedEventArgs e)
        {
            CheckPointEdit checkPointEdit = new CheckPointEdit();
            checkPointEdit.Owner = this;
            checkPointEdit.ShowDialog();
        }


        //设置机型按钮被点击时，弹出设置机型窗口
        private void SetProductMenu_Click(object sender, RoutedEventArgs e) {
            ProductEdit productEdit = new ProductEdit();
            productEdit.Owner = this;
            productEdit.ShowDialog();
        }


        //ComBox、TextBox边距
        static DependencyProperty BoxMarginProperty = DependencyProperty.Register(
            "BoxMargin",
            typeof(Thickness),
            typeof(MainWindow)
            );

        //ComBox、TextBox宽度
        static DependencyProperty BoxWidthProperty = DependencyProperty.Register(
            "BoxWidth",
            typeof(double),
            typeof(MainWindow)
            );

        //ComboBox、TextBox高度
        static DependencyProperty BoxHeightProperty = DependencyProperty.Register(
            "BoxHeight",
            typeof(double),
            typeof(MainWindow)
            );


        //机型选择、SN的边距
        static DependencyProperty LabelMarginProperty = DependencyProperty.Register(
            "LabelMargin",
            typeof(Thickness),
            typeof(MainWindow)
            );

        //机型选择、SN的字体大小
        static DependencyProperty LabelFontSizeProperty = DependencyProperty.Register(
            "LabelFontSize",
            typeof(double),
            typeof(MainWindow)
            );

        //状态的边距
        static DependencyProperty StatusMarginProperty = DependencyProperty.Register(
            "StatusMargin",
            typeof(Thickness),
            typeof(MainWindow)
            );

        //状态
        static DependencyProperty StatusProperty = DependencyProperty.Register(
            "Status",
            typeof(string),
            typeof(MainWindow),
            new PropertyMetadata("准备中")
            );

        //dBm边距
        static DependencyProperty DbmMarginProperty = DependencyProperty.Register(
            "DbmMargin",
            typeof(Thickness),
            typeof(MainWindow)
            );

        //功率的边距
        static DependencyProperty PowerMarginProperty = DependencyProperty.Register(
            "PowerMargin",
            typeof(Thickness),
            typeof(MainWindow)
            );

        //功率值
        static DependencyProperty PowerProperty = DependencyProperty.Register(
            "Power",
            typeof(string),
            typeof(MainWindow),
            new PropertyMetadata("")
            );

        //nm的边距
        static DependencyProperty NmMarginProperty = DependencyProperty.Register(
            "NmMargin",
            typeof(Thickness),
            typeof(MainWindow)
            );

        //波长的边距
        static DependencyProperty WavelengthMarginProperty = DependencyProperty.Register(
            "WavelengthMargin",
            typeof(Thickness),
            typeof(MainWindow)
            );


        //值字体的大小
        static DependencyProperty ValueSizeProperty = DependencyProperty.Register(
            "ValueSize",
            typeof(double),
            typeof(MainWindow)
            );

        //单位字体的大小(nm dBm)
        static DependencyProperty UnitSizeProperty = DependencyProperty.Register(
            "UnitSize",
            typeof(double),
            typeof(MainWindow)
            );

        //波长
        static DependencyProperty WavalengthProperty = DependencyProperty.Register(
            "Wavelength",
            typeof(String),
            typeof(MainWindow),
            new PropertyMetadata("")
            );

        //窗口大小变化时，刷新字体大小及位置
        private void FrameSize_Changed(object sender ,SizeChangedEventArgs args) {
            Grid grid = sender as Grid;
            double parentHeight = grid.ActualHeight; //获取父元素的高与宽
            double parentWidth = grid.ActualWidth;
            string name = grid.Name;
            switch (name)
            {
                case "StatusShowFrame":
                    double valueLabelHeight = Math.Round(parentHeight / 5, 1);  //值占1/5高度
                    double valueFontSize = Math.Round(valueLabelHeight / 1.27 , 1) + 9;
                    SetValue(ValueSizeProperty,valueFontSize); //设置值的字体大小
                    double unitFontSize = Math.Round(valueFontSize / 2, 1);
                    SetValue(UnitSizeProperty, unitFontSize); //设置单位的字体大小
                    //设置波长的边距
                    double left = Math.Round(parentWidth/3 ,1);
                    double wavelengthTop = Math.Round(parentHeight/10,1);
                    Thickness thickness = new Thickness(left, wavelengthTop, 0,0); //左边留1/3的空,顶部留1/10的空
                    SetValue(WavelengthMarginProperty,thickness);
                    //设置nm的边距
                    SetValue(NmMarginProperty, new Thickness(Math.Round(left + valueFontSize * 2.35 + 30 ,1), Math.Round(parentHeight/20*4,1),0,0));
                    //设置功率的边距
                    double powerTop = Math.Round(parentHeight/10*4,1);
                    SetValue(PowerMarginProperty,new Thickness(left,powerTop,0,0));
                    //dBm的边距
                    SetValue(DbmMarginProperty, new Thickness(Math.Round(left + valueFontSize * 2.35 + 30, 1), Math.Round(parentHeight / 20 * 10, 1), 0, 0));
                    //状态的边距
                    double statusTop = Math.Round(parentHeight/10*7,1);
                    SetValue(StatusMarginProperty, new Thickness(0, statusTop, 0, 0));
                    break;
                case "SelectTypeFrame":
                    //设置底部标签尺寸
                    double fontSize = Math.Round((parentHeight - 30) / 1.27,1);
                    SetValue(LabelFontSizeProperty, fontSize);
                    //设置底部ComboBox、TextBox的尺寸
                    double boxHeight = parentHeight - 30;
                    SetValue(BoxHeightProperty,boxHeight);
                    double boxWidth = Math.Round(parentWidth / 2,1);
                    SetValue(BoxWidthProperty, boxWidth);
                    //设置底部标签边距
                    double labelLeft = Math.Round((parentWidth - fontSize * 4.7 - boxWidth) / 2,1);
                    SetValue(LabelMarginProperty, new Thickness(labelLeft, 0, 0, 0));
                    //设置底部ComboBox、TextBox的边距
                    double boxLeft = Math.Round(labelLeft + fontSize * 4.7,1);
                    SetValue(BoxMarginProperty,new Thickness(boxLeft,0,0,0));
                    break;
            }
        }

        //帮助按钮被点击时，显示一个帮助窗口
        private void HelpMenu_Click(object sender, RoutedEventArgs e)
        {

        }

        //初始化机型列表
        private void InitProductNameBox()
        {
            ProductManagement productManagement = ProductManagement.GetInstance();
            List<string> productNameList = productManagement.GetProductList();
            ProductNameBox.ItemsSource = productNameList;
            string selectName = CurrentConfigManagement.GetIntance().GetSelectProductName();
            if (selectName == "") {
                ProductNameBox.SelectedIndex = 0;
            }
            else
            {
                ProductNameBox.SelectedValue = selectName;
            }
        }


        //选择的机型发生变化时，保存最新内容至本地
        private void ProductNameSelectionChanged(object sender,SelectionChangedEventArgs args) {
            object selection = ProductNameBox.SelectedValue;
            if (selection == null)
            {
                return;
            }
            string productName = ProductNameBox.SelectedValue.ToString().Trim();
            CurrentConfigManagement currrentConfig = CurrentConfigManagement.GetIntance();
            currrentConfig.SaveSeletProductName(productName);
        }


        //显示区域内容变更时，让滑块始终在最低端
        private void MoveScrollToEnd(object sender, TextChangedEventArgs args)
        {
            LogTextBox.ScrollToEnd();
        }


        /* 追加内容至日志Box 
        参数为追加的内容及颜色
        执行本方法自动换行
        */
        private void AppendLog(string text, Brush brush)
        {
            try
            {
                Task appendLogTask = new Task(() =>
                {
                    App.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        Run run = new Run();
                        run.Text = "\n" + text;
                        run.Foreground = brush;
                        LogParagragh.Inlines.Add(run);
                    }));
                });
                appendLogTask.Start();
            }
            catch (Exception) { }
        }


        //SN框内输入回车键时，启动测试
        private void EnterKeyDown(object sender,KeyEventArgs args) {
            if(args.Key == Key.Enter)
            {
                SnBox.IsEnabled = false;
                ProductNameBox.IsEnabled = false;
                MessageBox.Show("Test Start ...");
            }
        }


        //初始化测试步骤
        private void InitTestStepBox()
        {
            List<TestSteps> testSteps = CurrentConfigManagement.GetIntance().GetStepList();
            foreach (TestSteps step in testSteps) {
                switch (step)
                {
                    case TestSteps.Linear:
                        LinearBox.IsChecked = true;
                        LinearBox.Foreground = Brushes.Green;
                        break;
                    case TestSteps.Correct:
                        CorrectionBox.IsChecked = true;
                        CorrectionBox.Foreground = Brushes.Green;
                        break;
                    case TestSteps.CheckValue:
                        CheckValueBox.IsChecked = true;
                        CheckValueBox.Foreground = Brushes.Green;
                        break;
                }
            }
        }


        //测试步骤选中或取消选中时，保存配置文件
        private void TestStepButton_Click(object sender,RoutedEventArgs args) {
            CheckBox box = (CheckBox)sender;
            TestSteps step = TestSteps.Linear;
            switch (box.Name)
            {
                case "LinearBox":
                    step = TestSteps.Linear;
                    break;
                case "CorrectionBox":
                    step = TestSteps.Correct;
                    break;
                case "CheckValueBox":
                    step = TestSteps.CheckValue;
                    break;
            }
            #region 根据选中还是取消来确定是添加还是删除步骤
            if ((bool)box.IsChecked)
            {
                box.Foreground = Brushes.Green;
                CurrentConfigManagement.GetIntance().AddStep(step);
            }
            else
            {
                box.Foreground = Brushes.Black;
                CurrentConfigManagement.GetIntance().RemoveStep(step);
            }
            #endregion
        }
    }
}
